package com.jy.appmarket.cards;

import com.jy.appmarket.R;
import com.jy.appmarket.model.InstalledApkInfo;

import android.content.Context;
import android.content.Intent;
import android.text.format.Formatter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import it.gmariotti.cardslib.library.internal.Card;

public class InstalledAppUICard extends Card {

	private InstalledApkInfo mApkInfo;
	private ImageView mApkIconImgView;
	private TextView mApkNameTV;
	private TextView mApkSizeTV;
	private TextView mApkVersionName;
	private TextView mUninstallApkTV;
	private Button mOpenAppBT;
	private InstalledAppUICardOnClickListener mListener;

	public interface InstalledAppUICardOnClickListener{
		void onUninstallApp(InstalledApkInfo apkInfo);
	}
	
	public InstalledAppUICard(Context context, InstalledApkInfo apkInfo, InstalledAppUICardOnClickListener listener) {
		super(context, R.layout.installed_app_ui_card_layout);
		mApkInfo = apkInfo;
		mListener = listener;
	}
	
	@Override
	public void setupInnerViewElements(ViewGroup parent, View view) {
		mApkIconImgView = parent.findViewById(R.id.installed_app_icon);
		mApkNameTV = parent.findViewById(R.id.installed_app_name);
		mApkSizeTV = parent.findViewById(R.id.installed_app_size);
		mUninstallApkTV = parent.findViewById(R.id.installed_app_uninstall_app);
		mOpenAppBT = parent.findViewById(R.id.installed_app_open);
		mApkVersionName = parent.findViewById(R.id.installed_app_versoin);
		mApkIconImgView.setImageDrawable(mApkInfo.getApkIcon());
		mApkNameTV.setText(mApkInfo.getApkName());
		mApkSizeTV.setText("大小:"+ Formatter.formatFileSize(getContext(), mApkInfo.getFileSize()));
		mApkVersionName.setText("版本:"+mApkInfo.getApkVersionName());
		mUninstallApkTV.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mListener != null){
					mListener.onUninstallApp(mApkInfo);
				}
			}
		});
		
		mOpenAppBT.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try {
					Intent intent = getContext().getPackageManager().getLaunchIntentForPackage(
							mApkInfo.getPackageName());
					getContext().startActivity(intent);
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(getContext(), "打开失败", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
}
